package com.mindcraft.user.utils;



import com.mindcraft.base.utils.CommonConst;
import com.mindcraft.base.utils.MindCraftCache;
import com.mindcraft.base.utils.SpringUtilsAuTo;
import com.mindcraft.user.po.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

public class MindCraftUtil {


    

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static String getToken() {
        return MindCraftUtil.getRequest().getHeader(CommonConst.TOKEN_HEADER);
    }


    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                    // 根据网卡取本机配置的IP
                    ipAddress = InetAddress.getLocalHost().getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) {
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = null;
        }
        return ipAddress;
    }


    public static User getAdminUser() {
        User admin = (User) MindCraftCache.get(CommonConst.ADMIN);
        return admin;
    }


    public static Integer getUserId() {

        User user = null;
        try {
            user = (User) MindCraftCache.get(MindCraftUtil.getToken());
            return user == null ? null : user.getId();
        } catch (Exception e) {
            return user == null ? null : user.getId();
        }


    }

    public static User getCurrentUser() {
//        User user = (User) MindCraftCache.get(MindCraftUtil.getToken());
        User user = (User)MindCraftCache.get(MindCraftUtil.getToken());
        return user;

    }


    public static String getUsername() {
        User user = (User) MindCraftCache.get(MindCraftUtil.getToken());
        return user == null ? null : user.getUsername();
    }


}
